/* eslint-disable prefer-promise-reject-errors */
import axios from 'axios'
import store from '../store'
import {CHG_LOGIN} from '@/store/mutation-types'
import getters from '@/store/getter.ts'
import router from '../router'
const request = ({url, data = {}, method = 'post', ...rest}: RequestParams) => {
  console.log('环境变量' + JSON.stringify(data))
  const router = getters.routerList(store.state)
  let urlBase = ''
  router.map(function (item, index) {
    if (item.isChoose) {
      urlBase = item.baseUrl
    }
  })
  return axios({
    baseURL: urlBase,
    url,
    method,
    data,
    headers: {
      'X-TECHSTAR-TOKEN': store.state.userInfo.token || '',
    },
    ...rest,
  }).then(({data, status, config}) => {
    const info = data.data
    const {code, msg} = data
    // const lastTime = window.localStorage.getItem('logTime')
    // if (lastTime) {
    //   const now = new Date()
    //   const timeCha = DateMinus(lastTime)
    //   if ((timeCha - 120) > 0) {
    //     //退出登录
    //     const token = ''
    //     store.commit(CHG_LOGIN, {key:'token', value: token})
    //     router.push({
    //       name: 'Login',
    //     })
    //     window.localStorage.setItem('logTime', '')
    //     return
    //   } else {
    //     const nowTime = `${now.getTime()}`
    //     window.localStorage.setItem('logTime', nowTime)
    //   }
    // } else {
    //   const now = new Date()
    //   const nowTime = `${now.getTime()}`
    //   window.localStorage.setItem('logTime', nowTime)
    // }
    if (code === 0) {
      console.log(JSON.stringify(info))
      return info
    } else {
      if (code) {
        return Promise.reject({code, msg, info})
      }
    }
  }, err => {
    console.log('request error', err)
  })
}

function DateMinus (sDate:any) {
  const now = new Date()
  console.log('当前时间' + now.getTime())
  const day = (now.getTime() - Number(sDate)) / 1000 / 60
  return day
}

interface RequestParams {
  url: string
  data?: any
  method?: 'post' | 'get'
  [key: string]: any
}

export {request}
